package com.qfedu.sca.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qfedu.sca.common.param.UserAdd;
import com.qfedu.sca.common.param.UserLogin;
import com.qfedu.sca.common.vo.R;
import com.qfedu.sca.dao.UserDao;
import com.qfedu.sca.entity.User;
import com.qfedu.sca.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/8 10:02
 * @Modified:
 */
@Service
@RequiredArgsConstructor
@Slf4j
@RefreshScope //监听配置中心  自动更新
public class UserServiceImpl implements UserService {
    @Value("${newnum}") //属性注入 获取对应配置文件的内容
    private Integer num;
    private final StringRedisTemplate template;
    private final UserDao dao;

    @Override
    public R add(UserAdd add) {
        User user=new User();
        BeanUtils.copyProperties(add,user);
        user.setPassword(SecureUtil.sha1(SecureUtil.md5(user.getPassword())));
        user.setNum(num);
        user.setStatus("有效");
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        return dao.insert(user)>0?R.ok(""):R.fail("新增用户失败！");
    }

    @Override
    public R<List<User>> queryAll(String nickName) {
        //
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByDesc(User::getCreateTime);
        if(StringUtils.hasLength(nickName)){
            wrapper.like(User::getNickName,nickName);
        }

        return R.ok(dao.selectList(wrapper));
    }

    @Override
    public R login(UserLogin login) {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,login.getPhone());
        wrapper.eq(User::getPassword,SecureUtil.sha1(SecureUtil.md5(login.getPassword())));
        User user=dao.selectOne(wrapper);
        if(user!=null && user.getStatus().equals("有效")){
            //生成令牌
            String token=SecureUtil.sha256(user.getPhone());
            //存储
            template.opsForValue().set("sca:token:"+token,user.getId()+"");

            return R.ok(token);
        }
        return R.fail("亲，账号或密码错误!");
    }

    @Override
    public R logout(String token) {
        //必须有令牌
        log.info("令牌={}",token);
        if(StringUtils.hasLength(token)){
            if(template.hasKey("sca:token:"+token)){
                template.delete("sca:token:"+token);
                return R.ok("");
            }
        }
        return R.fail("亲，令牌无效！");
    }
}
